package com.mayikt;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @ClassName MyTask
 * @Author 蚂蚁课堂余胜军 QQ644064779 www.mayikt.com
 * @Version V1.0
 **/
public class MyTask {
    ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public void read() {
        lock.readLock().lock();
        System.out.println(">>>" + Thread.currentThread().getName() + ",正在读取锁开始");
        try {
            Thread.sleep(1000);
        } catch (Exception e) {

        }
        System.out.println(">>>" + Thread.currentThread().getName() + ",正在读取锁结束");
        lock.readLock().unlock();

    }

    public void write() {
        lock.writeLock().lock();
        System.out.println(">>>" + Thread.currentThread().getName() + ",正在写入锁开始");
        try {
            Thread.sleep(1000);
        } catch (Exception e) {

        }
        System.out.println(">>>" + Thread.currentThread().getName() + ",正在写入锁结束");
        lock.writeLock().unlock();
    }

    public static void main(String[] args) {
        MyTask myTask = new MyTask();
        for (int i = 0; i < 10; i++) {
            new Thread(() -> myTask.write()).start();
        }
        for (int i = 0; i < 10; i++) {
            new Thread(() -> myTask.read()).start();
        }

    }
}
